package com.ujson.chat.server.handler;

import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.common.handler.AbstractHandler;
import com.ujson.chat.common.proto.MessageProto;
import com.ujson.chat.server.listener.ServerChildChannelCloseListener;
import com.ujson.chat.server.processor.LoginProcessor;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h3>ujson-parent</h3>
 * <p>登录处理器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-23 21:40
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class LoginRequestHandler extends AbstractHandler {
    @Autowired
    private LoginProcessor loginProcessor;
    @Autowired
    private ServerChildChannelCloseListener serverChildChannelCloseListener;

    public MessageProto.MessageType getMessageType() {
        return MessageProto.MessageType.LOGIN_REQUEST;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LogUtil.info(log, "add a new channel connect.");
        // 添加子通道关闭的监听, 用于session管理
        ctx.channel()
                .closeFuture()
                .addListener(serverChildChannelCloseListener);
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!super.messageTypeCheck(ctx, msg)) {
            return ;
        }
        // startt business handle
        LogUtil.info(log, "login request read");
        loginProcessor.doLogin(ctx, (MessageProto.Message) msg);
    }
}
